/**
 * Created by wust on 2020-01-07 11:01:02
 * Copyright © 2020 wust. All rights reserved.
 */
package com.sc.demo1.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.sc.common.context.DefaultBusinessContext;
import com.sc.common.dto.WebResponseDto;
import com.sc.demo1.entity.demo.Demo;
import com.sc.demo1.entity.demo.DemoImport;
import com.sc.common.service.ImportService;
import com.sc.common.util.MyIdUtil;
import com.sc.common.util.MyStringUtils;
import com.sc.common.util.cache.DataDictionaryUtil;
import com.sc.demo1.core.dao.DemoMapper;
import com.sc.easyexcel.definition.ExcelDefinitionReader;
import com.sc.easyexcel.factory.DefinitionFactory;
import com.sc.easyexcel.factory.xml.XMLDefinitionFactory4commonImport;
import com.sc.easyexcel.resolver.poi.POIExcelResolver4commonImport;
import com.sc.easyexcel.result.ExcelImportResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayInputStream;
import java.util.*;

/**
 * @author: wust
 * @date: Created in 2020-01-07 11:01:02
 * @description:
 *
 */
@Service("demoImportServiceImpl")
public class DemoImportServiceImpl extends POIExcelResolver4commonImport implements ImportService {
    @Autowired
    private DemoMapper demoMapper;


    @Override
    protected ExcelDefinitionReader getExcelDefinition() {
        String xmlFullPath = "easyexcel/import/xml/demo.xml";
        DefinitionFactory definitionReaderFactory = new XMLDefinitionFactory4commonImport(xmlFullPath);
        return definitionReaderFactory.createExcelDefinitionReader();
    }

    @Override
    protected String getLookupItemCodeByName(String rootCode, String name) {
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();
        return DataDictionaryUtil.getLookupCodeByRootCodeAndName(ctx.getLocale().toString(),rootCode,name);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public WebResponseDto importByExcel(JSONObject jsonObject) {
        WebResponseDto responseDto = new WebResponseDto();

        ExcelImportResult excelImportResult = null;
        try {
            byte[] fileBytes = jsonObject.getBytes("fileBytes");

            super.excelInputStream =  new ByteArrayInputStream(fileBytes);

            // 1.读取excel数据
            excelImportResult = super.readExcel();

            // 2.处理业务数据
            Map<String, List<?>> listMap = excelImportResult.getListMap();

            List<DemoImport> imports = (List<DemoImport>)listMap.get("0"); // 获取第1个sheet里面的数据
            if(CollectionUtils.isNotEmpty(imports)){
                int successCount = 0;
                int errorCount = 0;
                String errorMsg = "";

                Map resultMap = doImport(imports);
                successCount = Integer.parseInt(resultMap.get("successCount")+"");
                errorCount = Integer.parseInt(resultMap.get("errorCount")+"");
                errorMsg = resultMap.get("errorMsg")+"";

                if(successCount == imports.size()){
                    responseDto.setCode("A100502");
                    errorMsg = "全部导入成功，共["+successCount+"]条记录" + errorMsg;
                }else if(errorCount == imports.size()){
                    responseDto.setCode("A100504");
                    errorMsg = "全部导入失败，共["+errorCount+"]条记录" + errorMsg;
                }else{
                    responseDto.setCode("A100503");
                    errorMsg = "部分导入成功，共["+successCount+"]条记录导入成功，["+errorCount+"]条记录导入失败" + errorMsg;
                }
                responseDto.setMessage(errorMsg);
            }else{
                responseDto.setCode("A100504");
                responseDto.setMessage("这是一个空Excel");
            }
        }catch (Exception e){
            e.printStackTrace();
            responseDto.setCode("A100504");
            if(MyStringUtils.isNotBlank(e.getMessage())){
                int length = e.getMessage().length() >= 500 ? 500 : e.getMessage().length();
                responseDto.setMessage(e.getMessage().substring(0,length));
            }else{
                int length = e.toString().length() >= 500 ? 500 : e.toString().length();
                responseDto.setMessage("导入失败:" + e.toString().substring(0,length));
            }
        }
        return responseDto;
    }


    private Map doImport(List<DemoImport> gatewayImports){
        DefaultBusinessContext ctx = DefaultBusinessContext.getContext();

        Map map = new HashMap();
        map.put("successCount",0);
        map.put("errorCount",0);
        map.put("errorMsg","");

        int successCount = 0;
        int errorCount = 0;
        // 错误信息
        StringBuffer errorMsg = new StringBuffer();

        List<Demo> listNew = new ArrayList();
        List<Demo> listOld = new ArrayList();
        for (DemoImport gatewayImport : gatewayImports) {
            if(gatewayImport.getSuccessFlag()){
                Map gatewayMap = DataDictionaryUtil.getGatewayByMac(gatewayImport.getMac());
                if(CollectionUtil.isNotEmpty(gatewayMap)){
                    Demo gateway = BeanUtil.mapToBean(gatewayMap,Demo.class,true);
                    if(gateway.getCompanyId() != null
                            && gateway.getProjectId() != null
                            && ((ctx.getBranchCompanyId().longValue() != gateway.getCompanyId().longValue()) || (ctx.getProjectId().longValue() != gateway.getProjectId().longValue()))){
                        errorMsg.append("<br/>").append("网关[" + gateway.getMac() + "]已经其他项目绑定。");
                        errorCount ++;
                    }else{
                        gateway.setName(gatewayImport.getName());
                        gateway.setType(gatewayImport.getType());
                        gateway.setModifyId(ctx.getAccountId());
                        gateway.setModifyName(ctx.getAccountName());
                        gateway.setModifyTime(new Date());
                        listOld.add(gateway);
                        successCount ++;
                    }
                }else{
                    gatewayImport.setId(MyIdUtil.getId());
                    gatewayImport.setProjectId(ctx.getProjectId());
                    gatewayImport.setCompanyId(ctx.getBranchCompanyId());
                    gatewayImport.setCreaterId(ctx.getAccountId());
                    gatewayImport.setCreaterName(ctx.getAccountName());
                    gatewayImport.setCreateTime(new Date());
                    listNew.add(gatewayImport);
                    successCount ++;
                }
            }else{
                errorMsg.append(gatewayImport.getErrorMessage()).append("\n");
                errorCount ++;
            }
        }

        map.put("successCount",successCount);
        map.put("errorCount",errorCount);
        map.put("errorMsg",errorMsg);

        // 新增
        if (CollectionUtils.isNotEmpty(listNew)) {
            demoMapper.insertList(listNew);
        }

        // 修改
        if (CollectionUtils.isNotEmpty(listOld)) {
            demoMapper.batchUpdate(listOld);
        }
        return map;
    }
}
